<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div
            class="flex items-center"
            style="display: flex; justify-content: space-between"
          >
            <div style="display: flex; align-items: center">
              <div>
                {{
                  route.query.readonly
                    ? "查看废料结算单信息"
                    : route.query.id
                    ? "编辑废料结算单信息"
                    : "新增废料结算单"
                }}
              </div>
              <el-tag
                v-if="route.query.code"
                :type="tagType"
                style="margin-left: 10px"
                >{{ route.query.code }}</el-tag
              >
            </div>
          </div>
        </template>
        <template #extra>
          <div>
            <el-button
              v-if="!readonly"
              class="button"
              type="primary"
              :loading="loading"
              @click="handleSubmit"
            >
              保 存
            </el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              ref="finalStatement"
              label-width="130px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="收款日期" prop="collectionDate">
                    <el-date-picker
                      v-model="form.collectionDate"
                      :disabled="Boolean(route.query.readonly)"
                      style="width: 100%"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收款项目" prop="collectionProject">
                    <el-input
                      v-model="form.collectionProject"
                      :disabled="Boolean(route.query.readonly)"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="付款单位编码" prop="collectionDept">
                    <el-input
                      v-model="form.collectionDept"
                      :disabled="Boolean(route.query.readonly)"
                      @click="visibleCustomer = true"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="付款单位" prop="collectionDeptName">
                    <el-input
                      v-model="form.collectionDeptName"
                      disabled
                      placeholder="选择付款单位自动带出"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收款方式" prop="collectionType">
                    <el-select
                      v-model="form.collectionType"
                      :disabled="Boolean(route.query.readonly)"
                      @change="changeCollectionType"
                      class="m-2"
                      placeholder="选择收款方式"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in mes_collection_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收款事由" prop="refundDate">
                    <el-input
                      v-model="form.collectionReason"
                      :disabled="Boolean(route.query.readonly)"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="上次结余">
                    <el-input
                      v-model="form.amountArrears"
                      maxlength="30"
                      disabled
                      placeholder="选择付款单位自动带出"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <!--                                <el-col :span="8">-->
                <!--                                    <el-form-item label="未结算金额">-->
                <!--                                        <el-input v-model="form.totalAmountUnsettled" maxlength="30"  style="width: 100%;" />-->
                <!--                                    </el-form-item>-->
                <!--                                </el-col>-->
                <el-col :span="8">
                  <el-form-item label="结算金额">
                    <el-input
                      v-model="form.amount"
                      maxlength="30"
                      @input="handleInput"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="本次结余">
                    <el-input
                      v-model="form.totalAmountArrears"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    v-if="flag"
                    label="银行卡号"
                    prop="bankcardNumber"
                    :rules="[
                      { required: true, message: '银行卡号', trigger: 'blur' },
                    ]"
                  >
                    <el-input
                      v-model="form.bankcardNumber"
                      maxlength="30"
                      style="width: 100%"
                      :disabled="Boolean(route.query.readonly)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    v-if="flag"
                    label="持卡人"
                    prop="cardholder"
                    :rules="[
                      { required: true, message: '持卡人', trigger: 'blur' },
                    ]"
                  >
                    <el-input
                      v-model="form.cardholder"
                      maxlength="30"
                      style="width: 100%"
                      :disabled="Boolean(route.query.readonly)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="创建人">
                    <el-input
                      v-model="form.createBy"
                      :disabled="Boolean(route.query.readonly)"
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建时间">
                    <el-input
                      v-model="form.createTime"
                      disabled
                      maxlength="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="上传发票">
                    <el-upload
                      :disabled="Boolean(route.query.readonly)"
                      :class="{ disabled: uploadDisabled }"
                      :limit="10"
                      :multiple="true"
                      :auto-upload="false"
                      :show-file-list="true"
                      :on-change="changePictureUpload"
                      v-model:file-list="fileList"
                      list-type="picture-card"
                      :accept="acceptedFileTypes"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                    >
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
<!--                        <el-button style="margin-bottom: 5px;" :disabled="readonly" type="primary" size="small" plain-->
            <!--                            icon="Plus" @click="handleChoice">从废料处理选择</el-button>-->
      <!-- <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">结算明细</span>
          </template>
          <div>
            
            <el-form ref="finalStatementForm" :model="mesWastesettleDetailList">
              <el-table
                :data="mesWastesettleDetailList"
                :summary-method="getSummaries"
                show-summary
                border
                style="width: 100%"
                :header-cell-class-name="must"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                  align="center"
                />
                <el-table-column
                  label="单据编码"
                  align="center"
                  prop="wasteCode"
                />
                <el-table-column
                  label="单据金额"
                  align="center"
                  prop="wasteSum"
                />
                
               
                <el-table-column label="备注" align="center" prop="remark" />
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse> -->

         <!-- <el-table-column label="处理日期" align="center" prop="wastesettleCode" /> -->
                <!--                                <el-table-column label="已收金额" align="center" prop="wasteReceived" />-->
                <!--                                <el-table-column label="未收金额" align="center" prop="wasteNoreceived" />-->
                <!--                                <el-table-column label="本次实收金额" align="center" prop="amount">-->
                <!--                                    <template #default="scope">-->
                <!--                                        &lt;!&ndash; <el-form-item class="margin0"-->
                <!--                                            :prop="'finalStatementForm.' + scope.$index + '.amount'"-->
                <!--                                            :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"> &ndash;&gt;-->
                <!--                                        <el-input v-model="scope.row.amount" :disabled="Boolean(route.query.readonly)"-->
                <!--                                            @change="sumPrice" @input="Comparison(scope.row)" type="number"-->
                <!--                                            style="width: 100%;"></el-input>-->
                <!--                                        &lt;!&ndash; </el-form-item> &ndash;&gt;-->
                <!--                                    </template>-->
                <!--                                </el-table-column>-->
                <!--                                <el-table-column label="是否结清" align="center" prop="isSettle">-->
                <!--                                    <template #default="scope">-->
                <!--                                        {{ getIsSettleText(scope.row) }}-->
                <!--                                    </template>-->
                <!--                                </el-table-column>-->
                <!--                                <el-table-column fixed="right" label="操作" align="center">-->
                <!--                                    <template #default="scope">-->
                <!--                                        <el-button link type="primary" :disabled="readonly" size="small"-->
                <!--                                            @click="handleDel(scope.row)">删除</el-button>-->
                <!--                                    </template>-->
                <!--                                </el-table-column>-->
    </el-card>
    <searchWaste
      :visible="visibleWaste"
      @changeUpdate="changeWasteData"
      @cancel="
        () => {
          visibleWaste = false;
        }
      "
    >
    </searchWaste>
    <SearchCustomer
      :visible="visibleCustomer"
      @changeUpdate="changeCustomerData"
      @cancel="
        () => {
          visibleCustomer = false;
        }
      "
    >
    </SearchCustomer>
  </div>
</template>

<script setup>
import { computed } from "vue";
import searchWaste from "./wasteList.vue";
import SearchCustomer from "@/components/SearchCustomer";
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();
import {
  getWastesettle,
  updateWastesettle,
  addWastesettle,
  addOrEditMesFile,
  getOrEditMesFile,
  delOrEditMesFile,
} from "@/api/scrap/finalStatement.js";
const { proxy } = getCurrentInstance();
const { mes_collection_type } = proxy.useDict("mes_collection_type");
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
import { listWasteJS } from "@/api/scrap/handle.js";
const router = useRouter();
const route = useRoute();
const activeNames = ["1"];
const finalStatement = ref(null);
const acceptedFileTypes = ref("image/*");
import { preview } from "vue3-preview-image";
const fileList = ref([]);
const loading = ref(false);

const mesWastesettleDetailList = ref([]);
const readonly = ref(false);
const finalStatementForm = ref(null);
const visibleCustomer = ref(false);
const visibleWaste = ref(false);
const flag = ref(false);
const data = reactive({
  form: {},
  rules: {
    refundMachineid: [
      { required: true, message: "请选择退库机台", trigger: "blur" },
    ],
    collectionProject: [
      { required: true, message: "收款项目不能为空", trigger: "blur" },
    ],
    collectionDept: [
      { required: true, message: "付款单位编码不能为空", trigger: "change" },
    ],
    collectionType: [
      { required: true, message: "付款方式不能为空", trigger: "change" },
    ],
  },
});
const { form, rules } = toRefs(data);
const userInfo = useUserStore();
const tagType = computed(() => {
  return route.query.status == 0 ? "" : "danger";
});
const queryParams = ref({
  pageNum: 1,
  pageSize: 100,
  status: 0,
  code: undefined,
  handleDept: undefined,
});
const sheetTotal = ref(0);
// 列显隐信息
const columns = ref([
  { key: 0, label: `单据编码`, visible: true },
  { key: 1, label: `单据金额`, visible: true },
  { key: 2, label: `备注`, visible: true },
]);
readonly.value = route.query.readonly;
// console.log('route.query', route.query)
if (route.query.id) {
  getWastesettle(route.query.id)
    .then((response) => {
      form.value = response.data;
      if (form.value.collectionType == "2") {
        flag.value = true;
      } else {
        flag.value = false;
      }
      form.value.collectionType = response.data.collectionType + "";
      response.data.mesWastesettleDetailList.forEach((ele) => {
        sheetTotal.value += ele.wasteSum;
      });
      mesWastesettleDetailList.value = response.data.mesWastesettleDetailList;
    })
    .then((response) => {
      getOrEditMesFile({ foreignKey: route.query.id, fileType: 10 }).then(
        (response2) => {
          console.log("response2", response2);
          fileList.value = response2.data;
          fileList.value.forEach((item) => {
            item.url = import.meta.env.VITE_APP_BASE_API + item.filePath;
          });
        }
      );
    });
} else {
  // console.log('userInfo', userInfo)
  form.value = {};
  form.value.createBy = userInfo.name;
  form.value.collectionProject = "废料处理";
  getCurrentTime();
}
const changeCollectionType = (value) => {
  if (value == "2") {
    flag.value = true;
  } else {
    flag.value = false;
  }
};

//发票上传
// 图片上传
const uploadDisabled = ref(false);
const changePictureUpload = (file) => {
  uploadDisabled.value = file?.url ? true : false;
};
const handleRemove = (uploadFile, uploadFiles) => {
  console.log("uploadFile", uploadFile);
  if (uploadFile.id) {
    delOrEditMesFile(uploadFile.id, route.query.id).then((response) => {
      console.log("response", response);
      if (response.code == 200) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }
    });
  }

  uploadDisabled.value = fileList.value.length >= 1;
};
const handlePictureCardPreview = (uploadFile, uploadFiles) => {
  preview(uploadFile.url);
};
// 上传图片
const uploadFile = async (fileList, fileType, id) => {
  console.log("fileList", fileList);
  try {
    for (const file of fileList) {
      if (file.raw) {
        const formData = new FormData();
        formData.append("isMultiple", 1);
        formData.append("foreignKey", id);
        formData.append("fileType", fileType);
        formData.append("file", file.raw);

        await addOrEditMesFile(formData);
      }
    }
  } catch (error) {
    console.error("Error uploading files:", error);
  }
};

// const uploadFile = (fileList, fileType, id) => {
//     console.log('fileList',fileList)
//     for (const file of fileList) {
//         if (file.raw) {
//             const formData = new FormData();
//             formData.append('foreignKey', id);
//             formData.append('fileType', fileType);
//             formData.append('file', file.raw);

//             addOrEditMesFile(formData).then(res => {
//                 // 处理上传成功后的逻辑
//             });
//         }
//     }
// }
function getIsSettleText(row) {
  const isSettle =
    Number(row.amount) == Number(row.wasteNoreceived) ||
    row.wasteNoreceived == 0.0;
  return isSettle ? "是" : "否";
}

function getCurrentTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return (form.value.collectionDate = `${year}-${month}-${day}`);
}

function getCreatTime() {
  // 获取当前时间
  var currentDate = new Date();
  // 获取年、月、日、时、分、秒
  var year = currentDate.getFullYear();
  var month = (currentDate.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以要加1，然后确保两位数字
  var day = currentDate.getDate().toString().padStart(2, "0");
  var hours = currentDate.getHours().toString().padStart(2, "0");
  var minutes = currentDate.getMinutes().toString().padStart(2, "0");
  var seconds = currentDate.getSeconds().toString().padStart(2, "0");

  // 生成当前年月日时分秒
  form.value.createTime =
    year +
    "-" +
    month +
    "-" +
    day +
    " " +
    hours +
    ":" +
    minutes +
    ":" +
    seconds;
}

const must = (obj) => {
  let mustColumns = [];
  mustColumns = [5];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const Comparison = (row) => {
  console.log("row", row);
  if (row.wasteNoreceived < row.amount) {
    row.amount = 0;
    ElMessage({
      message: "本次实收金额不能大于未收金额",
      type: "warning",
    });
  }
};

const sumPrice = () => {
  form.value.amount = mesWastesettleDetailList.value.reduce((sum, item) => {
    // 将 item.amount 转换为数字，如果不能转换，则使用 0
    const amount = Number(item.amount) || 0;
    return sum + amount;
  }, 0);
};

// 本次结余触发事件
const handleInput = (amount) => {
  //本次结余=上次结余+未结算合计-结算金额
  form.value.totalAmountArrears = Number(
    form.value.totalAmountUnsettled - amount
  ).toFixed(2);
};

const handleChoice = () => {
  visibleWaste.value = true;
};

const changeWasteData = (row) => {
  console.log("row", row);
  // 先将新元素添加到数组中
  // mesWastesettleDetailList.value.push(
  //     { wasteCode: row.code, wasteSum: row.amountSum, wasteReceived: row.amountReceived ? row.amountReceived : 0,
  //         wasteNoreceived: Number(row.amountSum - row.amountReceived).toFixed(2) });
  // // 去重操作
  // const uniqueMesWastesettleDetailList = mesWastesettleDetailList.value.reduce((acc, cur) => {
  //     // 检查当前元素的 wasteCode 是否已经存在于 acc 中
  //     if (!acc.hasOwnProperty(cur.wasteCode)) {
  //         // 如果不存在，则将当前元素的 wasteCode 添加到 acc 中，并将当前元素添加到结果数组中
  //         acc[cur.wasteCode] = cur;
  //     }
  //     return acc;
  // }, {});
  // // 将结果转换为数组
  // const result = Object.values(uniqueMesWastesettleDetailList);
  // mesWastesettleDetailList.value = result
  // visibleWaste.value = false;
  //清空之前的选择
  mesWastesettleDetailList.value = [];
  row.forEach((ele) => {
    ele.wasteCode = ele.code;
    ele.wasteSum = ele.amountSum;
    ele.wasteReceived = ele.amountReceived ? ele.amountReceived : 0;
    ele.wasteNoreceived = Number(ele.amountSum - ele.amountReceived).toFixed(2);
    mesWastesettleDetailList.value.push(ele);
  });
  mesWastesettleDetailList.value = uniqueByMaterialId(
    mesWastesettleDetailList.value
  );
  visibleWaste.value = false;
};

const uniqueByMaterialId = (list) => {
  const seenMaterialIds = {};
  return list.reduce((acc, curr) => {
    if (!seenMaterialIds[curr.id]) {
      seenMaterialIds[curr.id] = true;
      acc.push(curr);
    }
    return acc;
  }, []);
};

const changeCustomerData = (row) => {
  console.log("row", row);
  form.value.collectionDept = row.code;
  form.value.collectionDeptId = row.id;
  form.value.collectionDeptName = row.name;
  form.value.amountArrears = row.totalAmountArrears;
  queryParams.value.code = row.code;
  visibleCustomer.value = false;
  //获取上次结算金额
  getList();
  // 从这添加细表数据
};
const getList = async () => {
  //清空之前的选择
  mesWastesettleDetailList.value = [];
  sheetTotal.value = 0;
  loading.value = true;
  const res = await listWasteJS(queryParams.value);
  loading.value = false;
  //wasteList.value = res.rows
  // total.value = res.total
  res.rows.forEach((ele) => {
    ele.wasteCode = ele.code;
    ele.wasteSum = ele.amountSum ? ele.amountSum : 0;
    sheetTotal.value += ele.amountSum;
    ele.wasteReceived = ele.amountReceived ? ele.amountReceived : 0;
    ele.wasteNoreceived = Number(ele.wasteSum - ele.amountReceived).toFixed(2);
    mesWastesettleDetailList.value.push(ele);
  });
  //结算金额  默认是未结算金额可以修改
  form.value.amount = Number(
    form.value.amountArrears + sheetTotal.value
  ).toFixed(2);
  form.value.totalAmountArrears = 0.0;
  form.value.totalAmountUnsettled = Number(
    form.value.amountArrears + sheetTotal.value
  ).toFixed(2);
};
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    switch (column.property) {
      case "wasteSum":
        sums[index] = sheetTotal.value;
        break;
      default:
        break;
    }
  });
  return sums;
};

const handleDel = (row) => {
  console.log("row", row);
  const index = mesWastesettleDetailList.value.indexOf(row);
  if (index !== -1) {
    mesWastesettleDetailList.value.splice(index, 1);
    sumPrice();
  }
};
//保存
const handleSubmit = async () => {
  //只显示最后一次结算到目前为止未结算的明细。有可能最后一次没有结算完，并且之后没有明细，再次结算的时候是没有明细的，因此把校验去掉
  // if (!mesWastesettleDetailList.value.length) {
  //     ElMessage({
  //         message: '请至少存在一条结算明细',
  //         type: 'warning',
  //     });
  //     return
  // }
  // 使用 await 等待校验结果
  // await finalStatementForm.value.validate();
  const hasEmptyAmount = mesWastesettleDetailList.value.some(
    (item) => !item.amount && item.amount != 0
  );
  // if (hasEmptyAmount) {
  //     console.log('存在 amount 为空的情况');
  //     ElMessage({
  //         message: '请确保结算明细中填写本次实收金额',
  //         type: 'warning',
  //     });
  //     return
  // }
  // debugger
  // if(form.value.collectionType==2){//转账
  //      if(form.value.cardholder || form.value.cardholder =='' || form.value.bankcardNumber || form.value.bankcardNumber==''){
  //         ElMessage({
  //         message: '请填写银行卡号和持卡人',
  //         type: 'warning',
  //     });
  //      }
  // }
  // 校验通过
  finalStatement.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      const formData = form.value;
      formData.mesWastesettleDetailList = mesWastesettleDetailList.value;
      try {
        if (formData.id) {
          const response = await updateWastesettle(formData);
          if (response.code === 200) {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            if (fileList.value.length > 0) {
              await uploadFile(fileList.value, 10, route.query.id);
            }
            goBack();
            loading.value = false;
          }
        } else {
          formData.status = 0;
          const response = await addWastesettle(formData);
          if (response.code === 200) {
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            if (fileList.value.length > 0) {
              await uploadFile(fileList.value, 10, response.data);
            }
            goBack();
            loading.value = false;
          }
        }
      } catch (error) {
        console.error("Error:", error);
        loading.value = false;
        // 处理错误情况，例如提示用户或记录日志
      }
    }
  });

  // finalStatement.value.validate((valid) => {
  //     if (valid) {
  //         const formData = form.value;
  //         formData.mesWastesettleDetailList = mesWastesettleDetailList.value;
  //         if (formData.id) {
  //             updateWastesettle(formData).then(response => {
  //                 if (response.code === 200) {
  //                     ElMessage({
  //                         message: '编辑成功',
  //                         type: 'success',
  //                     });
  //                     fileList.value.length > 0 && uploadFile(fileList.value, 10, route.query.id)
  //                     goBack();
  //                 }
  //             });
  //         } else {
  //             formData.status = 0;
  //             addWastesettle(formData).then(response => {
  //                 console.log('response', response)
  //                 if (response.code === 200) {
  //                     ElMessage({
  //                         message: '新增成功',
  //                         type: 'success',
  //                     });
  //                     fileList.value.length > 0 && uploadFile(fileList.value, 10, response.data)
  //                     goBack();
  //                 }
  //             });
  //         }
  //     }
  // });
};

//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.back();
};

getCreatTime();
</script>

<style lang="scss" scoped>
:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}

.margin0 {
  margin-bottom: 0 !important;
}
</style>